package com.zhanghe.study.thread.callable01;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author zh
 * @date 2021/2/6 13:02
 */
public class TestCallable {

    public static void main(String[] args) {
        CallDemo call = new CallDemo();
        FutureTask<Integer> futureTask = new FutureTask<>(call);
        new Thread(futureTask).start();

        try {
            // get方法是一个阻塞方法  在没有执行结束之前一直阻塞，直到执行完毕
            int sum = futureTask.get();
            System.out.println("---------");
            System.out.println(sum);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

    }
}

/**
 * Callable相较于Runnable有返回值和异常
 */
class CallDemo implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for(int i = 0;i<1000;i++){
            sum +=i;
        }
        return sum;
    }
}
